package springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import springboot.Controller.dto.UserDTO;
import springboot.common.Constants;
import springboot.entity.LjhsUser;
import springboot.exception.ServiceException;
import springboot.mapper.LjhsUserMapper;
import springboot.service.ILjhsUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import springboot.utils.TokenUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hys
 * @since 2022-05-02
 */
@Service
public class LjhsUserServiceImpl extends ServiceImpl<LjhsUserMapper, LjhsUser> implements ILjhsUserService {
    private static final Log LOG=Log.get();
    @Override
    public UserDTO login(UserDTO userDTO) {
        LjhsUser one=getUserInfo(userDTO);
        if (one!=null){
            BeanUtil.copyProperties(one,userDTO,true);
            String token = TokenUtils.genToken(one.getUserId().toString(), one.getPassword());
            userDTO.setToken(token);
            return userDTO;
        }else{
            throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
        }
    }

    @Override
    public LjhsUser register(UserDTO userDTO) {
        LjhsUser one=getUserInfo(userDTO);
        if (one==null){
            one=new LjhsUser();
            BeanUtil.copyProperties(userDTO,one,true);
            save(one);
        }else{
            throw new ServiceException(Constants.CODE_600,"用户已存在");
        }
        return one;

    }
    private LjhsUser getUserInfo(UserDTO userDTO){
        QueryWrapper<LjhsUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userDTO.getUsername());
        queryWrapper.eq("password",userDTO.getPassword());
        LjhsUser one;
        try{
            one = getOne(queryWrapper);
        }catch (Exception e){
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        return one;
    }


}
